package com.hcc.repository.gen.engine.impl;

import com.hcc.repository.gen.engine.TemplateEngine;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Properties;

/**
 * Velocity模板引擎
 *
 * @author hushengjun
 * @date 2023/9/18
 */
public class VelocityTemplateEngine implements TemplateEngine {

    private final VelocityEngine velocityEngine;

    public VelocityTemplateEngine() {
        Properties p = new Properties();
        p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, "");
        p.setProperty(Velocity.INPUT_ENCODING, StandardCharsets.UTF_8.name());
        p.setProperty("file.resource.loader.unicode", "true");
        velocityEngine = new VelocityEngine(p);
        velocityEngine.init();
    }

    @Override
    public void generateFile(Map<String, Object> dataModel, String templatePath, File targetFile) {
        Template template = velocityEngine.getTemplate(templatePath, StandardCharsets.UTF_8.name());
        try (FileOutputStream fos = new FileOutputStream(targetFile);
             OutputStreamWriter ow = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
             BufferedWriter writer = new BufferedWriter(ow)) {
            template.merge(new VelocityContext(dataModel), writer);
        } catch (Exception e) {
            throw new RuntimeException(String.format("velocity模板：[%s]转换异常", templatePath), e);
        }
    }
}
